<template>
  <div class="consultant-container">
    <!-- 左侧列表 -->
    <div class="consultant-list">
      <el-scrollbar>
        <div
          v-for="consultant in consultantList"
          :key="consultant.id"
          :class="['consultant-item', { 'active': selectedId === consultant.id }]"
          @click="selectConsultant(consultant)"
        >
          <el-avatar v-if="consultant.avatar" :size="50" :src="proxy.globalInfo.imageUrl+consultant.avatar" />
          <el-avatar v-else :size="40" >
            <div class="icon">{{ (consultant.realName||"")[0]}}</div>
          </el-avatar>
          <div class="info">
            <h4 class="name">{{ consultant.realName }}</h4>
            <div class="meta">
              <el-rate
                v-model="consultant.rating"
                disabled
                :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
              />
            </div>
            <div class="expertise">
              <el-tag
                v-for="tag in consultant.specialtyArray"
                :key="tag"
                size="small"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
        </div>
      </el-scrollbar>
      <!-- 在列表底部添加加载状态 -->
      <div class="consultant-list">
        <!-- 原有列表内容 -->
        <div v-for="consultant in consultantList" :key="consultant.id">
          <!-- 原有列表项 -->
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-tip">
          <el-icon class="is-loading"><Loading /></el-icon>
          正在加载...
        </div>

        <!-- 没有更多提示 -->
        <div v-if="!hasMore" class="no-more">
          没有更多咨询师了
        </div>
    </div>
    </div>
    <!-- 右侧详情 -->
    <div class="consultant-detail" v-if="selectedConsultant">
      <div class="detail-header">
        <el-avatar :size="80" >
            <div class="icon">{{ (selectedConsultant.realName||"")[0]}}</div>
        </el-avatar>
        <div class="header-info">
          <h2>{{ selectedConsultant.realName }}</h2>
          <div class="sub-info">
            <span>从业 {{ selectedConsultant.experience }} 年</span>
            <el-rate
              v-model="selectedConsultant.rating"
              disabled
              show-text
              :texts="['极差', '失望', '一般', '满意', '惊喜']"
            />
          </div>
        </div>
      </div>

      <div class="detail-content">
        <!-- 基本信息 -->
        <div class="info-section">
          <h3>专业资质</h3>
          <ul class="qualification-list">
            <li v-for="(cert, index) in selectedConsultant.qualificationArray"
                :key="index">
              <el-icon><medal /></el-icon>
              {{ cert }}
            </li>
          </ul>
          <h3>个人简介</h3>
          <ul class="qualification-list">
            <div style="font-size: 18px;" v-html="selectedConsultant.introduction"></div>
          </ul>
        </div>


        <!-- 预约表单 -->
        <div class="appointment-form" >
          <el-form :model="appointmentForm"
                    ref="appointmentFormRef"
                     label-width="80px">
            <el-form-item label="预约时间">
              <el-date-picker
                v-model="appointmentForm.appointmentTime"
                type="dateTime"
                placeholder="Pick a day"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :size="size"
              />
            </el-form-item>
            <el-form-item label="咨询方式">
              <el-radio-group v-model="appointmentForm.method">
                <el-radio label="0">线下咨询</el-radio>
                <el-radio label="1">线上咨询</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                v-model="appointmentForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请描述您的主要问题（可选）"
              />
            </el-form-item>
          </el-form>
          <div class="submit-area">
            <el-button
              type="primary"
              size="large"
              @click="submitAppointment"
            >
              立即预约
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted ,reactive, getCurrentInstance, onBeforeUnmount ,nextTick } from "vue"
const { proxy } = getCurrentInstance();
import { Medal } from '@element-plus/icons-vue'

// 模拟数据
const consultantList = ref([
  {
    id: 1,
    name: '王心理咨询师',
    avatar: 'https://example.com/avatar1.jpg',
    rating: 4.5,
    price: 500,
    experience: 8,
    expertise: ['情绪管理', '亲密关系', '职场压力'],
    certifications: [
      '国家二级心理咨询师',
      '婚姻家庭咨询师（高级）',
      'EFT情绪聚焦治疗认证'
    ],
    timeSlots: [
      // 实际应从接口获取
      {
        startTime: new Date(2024, 5, 1, 14),
        endTime: new Date(2024, 5, 1, 15),
        available: true
      }
    ]
  }
])


const selectedId = ref(null)
const selectedConsultant = ref(null)
const selectedTime = ref(null)
const timeSlots = ref([])
const appointmentForm = ref({
  timeRange: [],
  method: 'video',
  remark: ''
})

// 选择咨询师
const selectConsultant = (consultant) => {
  selectedId.value = consultant.id
  selectedConsultant.value = consultant
  timeSlots.value = consultant.timeSlots
  selectedTime.value = null
}

// 选择时间
const selectTime = (slot) => {
  if (!slot.available) return
  selectedTime.value = slot
  appointmentForm.value.timeRange = [slot.startTime, slot.endTime]
}

// 格式化时间
const formatTime = (date) => {
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 禁用今天之前的日期
const disabledDate = (date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 将时间设置为今天的 00:00:00
  return date < today; // 如果日期小于今天，则禁用
};

const appointmentFormRef=ref();
// 提交预约
const submitAppointment = async () => {
  let valid = appointmentFormRef.value.validate();
  if(!valid){
    return;
  }
  if(disabledDate(appointmentForm.value.appointmentTime)){
    proxy.Message.error("只预约今天之后日期");
    return;
  }
  try {
    await proxy.Request({
      url: '/appointment/saveInfo',
      method: 'post',
      params: {
        counselorId: selectedConsultant.value.counselorId,
        method: appointmentForm.value.method,
        remark: appointmentForm.value.remark,
        appointmentTime:appointmentForm.value.appointmentTime,
      }
    })
    proxy.Message.success('预约成功,请在个人中心查看')
  } catch (error) {
    proxy.Message.error('预约失败')
  }
  appointmentForm.value={

  }
}

// 新增分页相关状态
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const hasMore = ref(true)

// 修改获取咨询师列表方法
const getConsultants = async () => {
  if (loading.value || !hasMore.value) return

  loading.value = true
  try {
    const res = await proxy.Request({
      url: "/counselor/loadCounselorList4User",
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })

    // 合并数据
    if (currentPage.value === 1) {
      consultantList.value = res.data.list
    } else {
      consultantList.value = [...consultantList.value, ...res.data.list]
    }

    // 更新分页状态
    total.value = res.data.total
    hasMore.value = currentPage.value * pageSize.value < total.value
    currentPage.value++

  } catch (error) {
    console.error('加载失败:', error)
  } finally {
    loading.value = false
  }
}
// 添加滚动监听
const handleScroll = () => {
  const scrollEl = document.querySelector('.consultant-list .el-scrollbar__wrap')
  if (!scrollEl) return

  const { scrollTop, scrollHeight, clientHeight } = scrollEl
  // 距离底部200px时加载
  if (scrollHeight - (scrollTop + clientHeight) < 200) {
    getConsultants()
  }
}

// 初始化时加载数据
onMounted(() => {
  getConsultants()
  document.querySelector('.consultant-list')
    .addEventListener('scroll', handleScroll)
})

// 销毁时移除监听
onBeforeUnmount(() => {
  document.querySelector('.consultant-list')
    ?.removeEventListener('scroll', handleScroll)
})


</script>

<style scoped lang="scss">
.consultant-container {
  display: flex;
  height: calc(100vh - 60px);
  background: #f5f7fa;

  .consultant-list {
    width: 320px;
    background: white;
    border-right: 1px solid #ebeef5;

    .consultant-item {
      display: flex;
      padding: 20px;
      cursor: pointer;
      transition: all 0.3s;
      border-bottom: 1px solid #f5f7fa;

      &.active {
        background: #f0f7ff;
      }

      .info {
        margin-left: 15px;
        flex: 1;

        .name {
          margin: 0 0 8px 0;
          color: #303133;
        }

        .meta {
          display: flex;
          align-items: center;
          margin-bottom: 8px;

          .price {
            margin-left: auto;
            color: #f56c6c;
            font-weight: 500;
          }
        }

        .expertise {
          :deep(.el-tag) {
            margin-right: 6px;
            margin-bottom: 4px;
          }
        }
      }
    }
  }

  .consultant-detail {
    flex: 1;
    padding: 30px;
    overflow-y: auto;

    .detail-header {
      display: flex;
      align-items: center;
      padding-bottom: 20px;
      border-bottom: 1px solid #ebeef5;

      .header-info {
        margin-left: 20px;

        h2 {
          margin: 0 0 8px 0;
          font-size: 24px;
        }

        .sub-info {
          display: flex;
          align-items: center;
          gap: 20px;
          color: #606266;
        }
      }
    }

    .info-section {
      margin: 25px 0;
      padding: 20px;
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(0,0,0,0.05);

      h3 {
        margin: 0 0 15px 0;
        color: #303133;
        font-size: 18px;
      }

      .qualification-list {
        list-style: none;
        padding: 0;

        li {
          padding: 8px 0;
          display: flex;
          align-items: center;
          gap: 8px;
          color: #606266;
        }
      }

      .time-slots {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;

        .time-tag {
          cursor: pointer;
          transition: all 0.3s;

          &:hover {
            transform: translateY(-2px);
          }
        }
      }
    }

    .appointment-form {
      margin-top: 30px;
      padding: 20px;
      background: white;
      border-radius: 8px;

      .submit-area {
        margin-top: 30px;
        text-align: center;
      }
    }
  }
}
.loading-tip {
  padding: 20px;
  text-align: center;
  color: #909399;

  .el-icon {
    margin-right: 8px;
    animation: rotating 2s linear infinite;
  }
}

.no-more {
  padding: 20px;
  text-align: center;
  color: #c0c4cc;
  font-size: 14px;
}

@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>